package com.base.cn.platform.os.service.course.cou.buy;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.number.AmountUtils;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.course.CourseType;
import com.base.cn.platform.os.dao.course.cou.buy.CourseBuyRecordDao;
import com.base.cn.platform.os.entity.course.catalog.CourseCatalog;
import com.base.cn.platform.os.entity.course.cou.Course;
import com.base.cn.platform.os.entity.course.cou.CourseProfile;
import com.base.cn.platform.os.entity.course.cou.buy.CourseBuyPackageCourse;
import com.base.cn.platform.os.entity.course.cou.buy.CourseBuyRecord;
import com.base.cn.platform.os.entity.course.cou.buy.CourseBuyRecordExpand;
import com.base.cn.platform.os.entity.course.cou.packageCou.PackageCourse;
import com.base.cn.platform.os.entity.course.cou.record.CoursePlayRecord;
import com.base.cn.platform.os.entity.course.cou.record.UserBuyCourseStudySpeed;
import com.base.cn.platform.os.entity.exam.record.ExamRecord;
import com.base.cn.platform.os.entity.qa.qareply.QaReply;
import com.base.cn.platform.os.service.course.catalog.CourseCatalogBiz;
import com.base.cn.platform.os.service.course.cou.CourseBiz;
import com.base.cn.platform.os.service.course.cou.CourseProfileBiz;
import com.base.cn.platform.os.service.course.cou.packageCou.PackageCourseBiz;
import com.base.cn.platform.os.service.course.cou.record.CoursePlayRecordBiz;
import com.base.cn.platform.os.service.exam.record.ExamRecordService;
import com.base.cn.platform.os.service.manage.user.user.SetUserDataService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 课程购买记录Biz
 *
 * @author s.li
 * @create 2018-05-17-14:41
 */
@Service
public class CourseBuyRecordBiz extends BaseBiz<CourseBuyRecord,CourseBuyRecordDao> {

    @Autowired
    private CourseBiz courseBiz;
    @Autowired
    private PackageCourseBiz packageCourseBiz;
    @Autowired
    private CourseBuyPackageCourseBiz courseBuyPackageCourseBiz;
    @Autowired
    private CourseProfileBiz courseProfileBiz;
    @Autowired
    private CoursePlayRecordBiz coursePlayRecordBiz;
    @Autowired
    private CourseCatalogBiz courseCatalogBiz;
    @Autowired
    private CourseBuyRecordDao courseBuyRecordDao;
    @Autowired
    private SetUserDataService<CourseBuyRecord> setUserDataService;
    @Autowired
    private ExamRecordService examRecordService;

    /**
     * 查询课程购买的用户列表
     * @param courseId 课程ID
     * @param page 分页条件
     * @return PageInfo<CourseBuyRecord>
     */
    public PageInfo<CourseBuyRecord> findCourseBuyUserList(BigDecimal courseId,Pagination page){
        CourseBuyRecord courseBuyRecord = new CourseBuyRecord();
        courseBuyRecord.setCourseId(courseId);
        PageHelper.startPage(page.getCurrentPage(),page.getPageSize());
        Page<CourseBuyRecord> classesPage =  courseBuyRecordDao.findCourseBuyUserList(CourseBuyRecord.class,courseBuyRecord);
        PageInfo<CourseBuyRecord> recordPageInfo =  new PageInfo<>(classesPage);
        setUserDataService.setUserData(recordPageInfo.getList(),true);
        return recordPageInfo;
    }


    /**
     * 验证用户是否购买的某一课程，并且返回购买记录所有的数据
     * @param userId 用户ID
     * @param courseId 课程ID
     * @param setCourseData 是否设置课程数据
     * @param setPackageCourseData 如果是套餐课程，是否设置套餐下的课程数据
     * @return CourseBuyRecord
     */
    public CourseBuyRecord checkUserBuyCourse(BigDecimal userId,
                                              BigDecimal courseId,
                                              boolean setCourseData,
                                              boolean setPackageCourseData){
        CourseBuyRecord courseBuyRecord = this.checkUserBuyCourse(userId,courseId);
        if(ObjectUtils.isNotEmpty(courseBuyRecord) ){
            courseBuyRecord = this.setCourseData(courseBuyRecord,setCourseData);
            courseBuyRecord = this.setPackageCourseData(courseBuyRecord,setPackageCourseData);
        }
        return courseBuyRecord;
    }

    /**
     * 检测用户是否购买过该课程
     * @param userId
     * @param courseId
     * @return CourseBuyRecord 返回null则未购买过
     */
    public CourseBuyRecord checkUserBuyCourse(BigDecimal userId,BigDecimal courseId){
        if(DataUtil.idIsNotNull(userId) && DataUtil.idIsNotNull(courseId)){
            CourseBuyRecord courseBuyRecord = new CourseBuyRecord();
            courseBuyRecord.setUserId(userId);
            courseBuyRecord.setCourseId(courseId);
            courseBuyRecord.setCourseStatus("SUCCESS");
            List<CourseBuyRecord> courseBuyRecordList = this.findCourseBuyRecordByUserId(courseBuyRecord,false);
            if(ObjectUtils.isNotEmpty(courseBuyRecordList)){
                return courseBuyRecordList.get(0);
            }
        }
        return null;
    }

    /**
     * 修改课程过期时间
     * @param detailsId
     * @param validTime
     */
    public void updateCourseBuyRecordValidTime(BigDecimal detailsId, Date validTime){
        CourseBuyRecord record = new CourseBuyRecord();
        record.setValidTime(validTime);
        this.updateByWhereSql(record," detailsId="+detailsId);
    }

    /**
     * 保存课程购买记录
     * @param courseBuyRecordList
     */
    @Transactional(rollbackFor = IllegalArgumentException.class )
    public void createCourseBuyRecord(List<CourseBuyRecord> courseBuyRecordList){
        if(ObjectUtils.isNotEmpty(courseBuyRecordList)){
            courseBuyRecordList.forEach(buyRecord->{
                //过期类型，1天数，2时间段（用于课程商品）
                if(buyRecord.getValidType()==1){
                    Integer  validDay = buyRecord.getValidDay();
                    buyRecord.setValidTime(DateUtils.addDays(new Date(),validDay));
                }else if (buyRecord.getValidType()==2){
                    buyRecord.setValidTime(buyRecord.getValidTime());
                }
            });
            this.batchSave(courseBuyRecordList);
            String courseIds = courseBuyRecordList.stream().map(e->e.getCourseId().toString()).distinct().collect(Collectors.joining(","));
            List<CourseProfile>  courseProfileList = courseProfileBiz.find("id in ("+courseIds+")",null,null);
            if(ObjectUtils.isNotEmpty(courseProfileList)){
                List<CourseProfile> _list = new ArrayList<>();
                courseProfileList.forEach(e->{
                    CourseProfile profile = new CourseProfile();
                    profile.setId(e.getId());
                    profile.setBuyCount(e.getBuyCount().intValue() +1);
                    _list.add(profile);
                });
                courseProfileBiz.updateBatch(_list);
            }
        }
    }

    /**
     * 通过流水ID，修改课程购买记录状态
     * @param detailsId 流水ID
     * @param courseStatus  课程状态，SUCCESS可使用，REFUND退费，CLOSE关闭
     */
    public void updateRecordCourseStatusByDetailsId(BigDecimal detailsId, String courseStatus) {
        CourseBuyRecord record = new CourseBuyRecord();
        record.setCourseStatus(courseStatus);
        this.updateByWhereSql(record," detailsId="+detailsId);
    }

    /**
     * 分页查询用户购买记录
     * @param courseBuyRecord 查询条件
     * @param page 分页条件
     * @param setCourseData 是否设置课程
     * @param setTeacherData 是否设置讲师数量
     * @param setProfileData 是否设置课程扩展数据
     * @param setStudySpeed 是否设置课程学习进度
     * @param setStudySumTime 是否设置总学习时间
     * @param setWeekStudyTime 是否设置一周的学习时间
     * @param setLastStudyCatalog 是否设置最后一个学习的目录
     * @return PageInfo<CourseBuyRecord>
     */
    public PageInfo<CourseBuyRecord> findCourseBuyRecordPage(CourseBuyRecord courseBuyRecord,
                                                             Pagination page,
                                                             boolean setCourseData,
                                                             boolean setTeacherData,
                                                             boolean setProfileData,
                                                             boolean setStudySpeed,
                                                             boolean setStudySumTime,
                                                             boolean setWeekStudyTime,
                                                             boolean setLastStudyCatalog){
        PageInfo<CourseBuyRecord> courseBuyRecordPageInfo = this.findCourseBuyRecordPage(courseBuyRecord,page,setCourseData);
        this.setCourseData(courseBuyRecordPageInfo.getList(),setCourseData,
                setTeacherData,setProfileData,setStudySpeed,
                setStudySumTime,setWeekStudyTime,setLastStudyCatalog);
        return courseBuyRecordPageInfo;
    }

    /**
     * 分页查询用户购买记录
     * @param courseBuyRecord 查询条件
     * @param page 分页条件
     * @param setCourseData 是否设置课程
     * @return PageInfo<CourseBuyRecord>
     */
    public PageInfo<CourseBuyRecord> findCourseBuyRecordPage(CourseBuyRecord courseBuyRecord, Pagination page,boolean setCourseData){
        PageInfo<CourseBuyRecord> courseBuyRecordPageInfo = this.findPage(this.getWhereSql(courseBuyRecord),page,null);
        this.setCourseData(courseBuyRecordPageInfo.getList(),setCourseData);
        return courseBuyRecordPageInfo;
    }

    /**
     * 查询课程购买记录（不分页）
     * @param courseBuyRecord
     * @param setCourseData
     * @return
     */
    public List<CourseBuyRecord> findCourseBuyRecordList(CourseBuyRecord courseBuyRecord, boolean setCourseData){
        String whereSql = this.getWhereSql(courseBuyRecord);
        List<CourseBuyRecord> courseBuyRecords = this.find(whereSql, null, null);
        return this.setCourseData(courseBuyRecords, setCourseData);
    }

    /**
     * 查询用户的购买课程记录（有效期内的）
     * @param courseBuyRecord
     * @param setCourseData
     * @return
     */
    public List<CourseBuyRecord> findCourseBuyRecordByUserId(CourseBuyRecord courseBuyRecord, boolean setCourseData){
        courseBuyRecord.setValidTime(new Date());
        courseBuyRecord.setCourseStatus("SUCCESS");
        String whereSql = this.getWhereSql(courseBuyRecord);
        List<CourseBuyRecord> courseBuyRecords = this.find(whereSql, null, null);
        return this.setCourseData(courseBuyRecords, setCourseData);
    }

    /**
     * 获取播放的购买记录
     * @param id 记录ID
     * @return
     */
    public CourseBuyRecord findPlayCourseBuyRecordById(BigDecimal id){
        CourseBuyRecord record = this.findById(id);
        record = this.setCourseData(record,true);
        if(ObjectUtils.isNotEmpty(record)){
            //如果是套餐，则获取套餐下已激活的课程
            if(record.getCourseTypeKey().equals(CourseType.COURSE_TYPE_PACKAGE.getKey())){
                List<CourseBuyPackageCourse> courseBuyPackageCourseList = courseBuyPackageCourseBiz.findCourseBuyPackageCourseByPackageIds(record.getCourseId().toString(),record.getUserId(),true);
                record.setCourseBuyPackageCourseList(courseBuyPackageCourseList);
            }
        }
        return record;
    }

    /**
     * 通过ID获取购买记录（用于查询用户播放）
     * @param id 记录ID
     * @param userId 用户ID
     * @param setCourseData 是否设置套餐数据
     * @param setPackageCourseData 是否设置套餐下课程课程数据（套餐类型的记录才起作用）
     * @return CourseBuyRecord
     */
    public CourseBuyRecord findCourseBuyRecordById(BigDecimal id,BigDecimal userId,
                                                   boolean setCourseData,
                                                   boolean setPackageCourseData){
        CourseBuyRecord record = new CourseBuyRecord();
        record.setUserId(userId);
        record.setId(id);
        record.setValidTime(new Date());
        CourseBuyRecord courseBuyRecord = this.findOne(this.getWhereSql(record),null);
        if(ObjectUtils.isNotEmpty(courseBuyRecord)){
            if(courseBuyRecord.getUserId().compareTo(userId)!=0){
                return null;
            }
            courseBuyRecord = this.setCourseData(courseBuyRecord,setCourseData);
            courseBuyRecord = this.setPackageCourseData(courseBuyRecord,setPackageCourseData);
        }
        return courseBuyRecord;
    }

    /**
     * 激活套餐课程
     * @param record 购买记录对象
     * @param courseIdArr 选择的课程ID数组
     */
    @Transactional(rollbackFor = IllegalArgumentException.class)
    public void activationPackage(CourseBuyRecord record, String[] courseIdArr) {
        List<CourseBuyPackageCourse> courseBuyPackageCourseList = new ArrayList<>();
        Arrays.stream(courseIdArr).forEach(courseId->{
            courseBuyPackageCourseList.add(courseBuyPackageCourseBiz.getCourseBuyPackageCourse(record.getOrderId(),record.getOrderNo(),record.getUserId(),record.getCourseId(),new BigDecimal(courseId)));
        });
        //生成套餐的激活记录
        courseBuyPackageCourseBiz.createCourseBuyPackageCourse(courseBuyPackageCourseList);
        record.setStatus(1);//设置成已激活
        this.updateById(record,null);
    }

    /**
     * 通过流水ID获取购买记录
     * @param detailsId 记录ID
     * @param setCourseData 是否设置课程数据
     * @return CourseBuyRecord
     */
    public CourseBuyRecord findCourseBuyRecordByDetailsId(BigDecimal detailsId, boolean setCourseData) {
        CourseBuyRecord record = this.findOne(" detailsId="+detailsId,null);
        record = this.setCourseData(record,setCourseData);
        return record;
    }

    /**
     * 更新激活状态，用于手动激活套餐课程
     * @param record 记录对象
     * @param status 状态，0未激动，1已激活
     * @param courseIds 课程ID串
     */
    @Transactional(rollbackFor = IllegalArgumentException.class )
    public void updateCourseBuyRecordStatus(CourseBuyRecord record,int status,String courseIds){
        record.setStatus(status);
        this.updateById(record,null);
        if(StringUtils.isNotEmpty(courseIds)){
            String[] arr = courseIds.split(",");
            List<CourseBuyPackageCourse> packageCourseList  = new ArrayList<>();
            Arrays.stream(arr).forEach(courseId->{
                CourseBuyPackageCourse courseBuyPackageCourse = new CourseBuyPackageCourse();
                courseBuyPackageCourse.setOrderId(record.getOrderId());
                courseBuyPackageCourse.setOrderNo(record.getOrderNo());
                courseBuyPackageCourse.setUserId(record.getUserId());
                courseBuyPackageCourse.setPackageId(record.getCourseId());
                courseBuyPackageCourse.setCourseId(new BigDecimal(courseId));
                packageCourseList.add(courseBuyPackageCourse);
            });
            //添加激活记录
            courseBuyPackageCourseBiz.createCourseBuyPackageCourse(packageCourseList);
        }
    }

    /**
     * 用户购买课程的Ids
     * @param userId
     * @return
     */
    public String  queryBuyCourseIdsByUserId(BigDecimal userId){
        String courseIds ="";
        if (DataUtil.idIsNotNull(userId)){
            CourseBuyRecord courseBuyRecord = new CourseBuyRecord();
            courseBuyRecord.setUserId(userId);
            List<CourseBuyRecord> buyRecords=findCourseBuyRecordByUserId(courseBuyRecord,false);
            courseIds = buyRecords.stream().map(e -> e.getCourseId().toString()).distinct().collect(Collectors.joining(","));
        }
        return courseIds;
    }
    //===============================================================================================
    /**
     * 设置课程购买记录下的套餐数据（如果购买的是套餐）
     * @param courseBuyRecord
     * @param setPackageCourseData
     * @return CourseBuyRecord
     */
    public CourseBuyRecord setPackageCourseData(CourseBuyRecord courseBuyRecord,boolean setPackageCourseData){
        if(courseBuyRecord.getCourse()!=null && courseBuyRecord.getCourseTypeKey().equals(CourseType.COURSE_TYPE_PACKAGE.getKey())){
            if(courseBuyRecord.getStatus().intValue()==1){//套餐已激活
                List<CourseBuyPackageCourse> courseBuyPackageCourseList = courseBuyPackageCourseBiz.findCourseBuyPackageCourseByPackageIds(courseBuyRecord.getCourseId().toString(),courseBuyRecord.getUserId(),true);
                courseBuyRecord.setCourseBuyPackageCourseList(courseBuyPackageCourseList);
            }else{//套餐未激活，获取套餐课程下的课程数据
                List<PackageCourse> packageCourseList = packageCourseBiz.findPackageCourseByPackageId(courseBuyRecord.getCourseId(),setPackageCourseData);
                courseBuyRecord.getCourse().setPackageCourseList(packageCourseList);
            }
        }
        return courseBuyRecord;
    }

    /**
     * 设置课程数据
     * @param courseBuyRecord
     * @param setCourseData
     * @return CourseBuyRecord
     */
    private CourseBuyRecord setCourseData(CourseBuyRecord courseBuyRecord,boolean setCourseData){
        if(ObjectUtils.isNotEmpty(courseBuyRecord) && setCourseData){
            List<CourseBuyRecord> courseBuyRecordList = new ArrayList<>();
            courseBuyRecordList.add(courseBuyRecord);
            courseBuyRecordList = setCourseData(courseBuyRecordList,setCourseData);
            courseBuyRecord = courseBuyRecordList.get(0);
        }
        return courseBuyRecord;
    }

    /**
     * 设置课程数据
     * @param courseBuyRecordList
     * @param setCourseData
     * @return List<CourseBuyRecord>
     */
    private List<CourseBuyRecord> setCourseData(List<CourseBuyRecord> courseBuyRecordList,boolean setCourseData){
        return this.setCourseData(courseBuyRecordList,setCourseData,false,false,false,false,false,false);
    }

    /**
     * 设置课程数据
     * @param courseBuyRecordList
     * @param setCourseData 是否设置课程数据
     * @param setTeacherData 是否设置课程老师数据
     * @param setProfileData 是否设置课程扩展数据
     * @param setStudySpeed 是否设置学习进度
     * @param setStudySumTime 是否设置总学习时间
     * @param setWeekStudyTime 是否设置一周的学习时间
     * @param setLastStudyCatalog 是否设置最后一个学习的目录
     * @return List<CourseBuyRecord>
     */
    private List<CourseBuyRecord> setCourseData(List<CourseBuyRecord> courseBuyRecordList,
                                                boolean setCourseData,
                                                boolean setTeacherData,
                                                boolean setProfileData,
                                                boolean setStudySpeed,
                                                boolean setStudySumTime,
                                                boolean setWeekStudyTime,
                                                boolean setLastStudyCatalog){
        if(ObjectUtils.isNotEmpty(courseBuyRecordList)){
            BigDecimal userId = courseBuyRecordList.get(0).getUserId();
            String courseIds = courseBuyRecordList.stream().map(e->e.getCourseId().toString()).distinct().collect(Collectors.joining(","));
            if(setCourseData){//设置课程数据
                Map<BigDecimal,Course> courseMaps = courseBiz.findCourseToMapByIds(courseIds,setTeacherData,false,false,setProfileData);
                courseBuyRecordList.forEach(e->{
                    Course course = courseMaps.get(e.getCourseId());
                    e.setCourse(course);
                });
            }
            if(setStudySpeed){//设置学习进度
                Map<Boolean,List<CourseBuyRecord>> courseBuyRecordListMap = courseBuyRecordList.stream().collect(Collectors.groupingBy(e->e.getStatus().intValue()==1));
                List<CourseBuyRecord> _list = courseBuyRecordListMap.get(true);//已经激活的课程
                if(ObjectUtils.isNotEmpty(_list)){
                    //区分套餐与非套餐购买记录
                    Map<Boolean,List<CourseBuyRecord>> mapList = _list.stream().collect(Collectors.groupingBy(e->e.getCourseTypeKey().equals(CourseType.COURSE_TYPE_PACKAGE.getKey())));
                    List<CourseBuyRecord> isPackageList = mapList.get(true);//套餐列表
                    Set<BigDecimal> courseIdSet = new HashSet<>();
                    //查询套餐已经激活的课程数据列表
                    List<CourseBuyPackageCourse> courseBuyPackageCourseList = null;
                    if(ObjectUtils.isNotEmpty(isPackageList)){
                        //套餐ID串
                        String packageIds = isPackageList.stream().map(e->e.getCourseId().toString()).distinct().collect(Collectors.joining(","));
                        //查询套餐已经激活的课程数据列表
                        courseBuyPackageCourseList = courseBuyPackageCourseBiz.findCourseBuyPackageCourseByPackageIds(packageIds,userId,false);
                        if(ObjectUtils.isNotEmpty(courseBuyPackageCourseList)){
                            courseBuyPackageCourseList.forEach(e->{
                                courseIdSet.add(e.getCourseId());
                            });
                        }
                    }
                    List<CourseBuyRecord> isCourseList = mapList.get(false);//非套餐列表
                    if(ObjectUtils.isNotEmpty(isCourseList)){
                        isCourseList.forEach(e->{
                            courseIdSet.add(e.getCourseId());
                        });
                    }
                    if(ObjectUtils.isNotEmpty(courseIdSet)){
                        String allCourseIds = courseIdSet.stream().map(e->e.toString()).collect(Collectors.joining(","));
                        Map<String,String> params = new HashMap<>();
                        params.put("userId",userId.toString());
                        params.put("courseIds",allCourseIds);
                        List<UserBuyCourseStudySpeed> userBuyCourseStudySpeeds = coursePlayRecordBiz.findUserBuyCourseStudySpeed(params);
                        if(ObjectUtils.isNotEmpty(userBuyCourseStudySpeeds)){
                            Map<BigDecimal,List<UserBuyCourseStudySpeed>> userBuyCourseStudySpeedListMap = userBuyCourseStudySpeeds.stream().collect(Collectors.groupingBy(e->e.getCourseId()));
                            //计算非套餐课程学习进度
                            if(ObjectUtils.isNotEmpty(isCourseList)){
                                isCourseList.forEach(e->{
                                    List<UserBuyCourseStudySpeed> studySpeedsList = userBuyCourseStudySpeedListMap.get(e.getCourseId());
                                    if(ObjectUtils.isNotEmpty(studySpeedsList)){
                                        setCourseBuyRecordStudySpeed(studySpeedsList,e);
                                    }
                                });
                            }
                            //计算套餐课程学习进度
                            if(ObjectUtils.isNotEmpty(isPackageList) && ObjectUtils.isNotEmpty(courseBuyPackageCourseList)){
                                //通过套餐ID分组
                                Map<BigDecimal,List<CourseBuyPackageCourse>> packageCourseListMap = courseBuyPackageCourseList.stream().collect(Collectors.groupingBy(e->e.getPackageId()));
                                isPackageList.forEach(e->{
                                    //套餐下所有课程的学习进度数据列表
                                    List<UserBuyCourseStudySpeed> studySpeeds = new ArrayList<>();
                                    //得到套餐已激活的课程数据列表
                                    List<CourseBuyPackageCourse> _packageCourseList = packageCourseListMap.get(e.getCourseId());
                                    if(ObjectUtils.isNotEmpty(_packageCourseList)){
                                        //获取套餐下每个课程的学习进度数量
                                        _packageCourseList.forEach(em ->{
                                            List<UserBuyCourseStudySpeed> _studySpeeds = userBuyCourseStudySpeedListMap.get(em.getCourseId());
                                            if(ObjectUtils.isNotEmpty(_studySpeeds)){
                                                studySpeeds.addAll(_studySpeeds);
                                            }
                                        });
                                    }
                                    if(ObjectUtils.isNotEmpty(studySpeeds)){
                                        setCourseBuyRecordStudySpeed(studySpeeds,e);
                                    }
                                });
                            }
                        }
                    }
                }
            }
            //设置课程总学习时间
            if(setStudySumTime){
                List<CoursePlayRecord> coursePlayRecordList = coursePlayRecordBiz.queryUserStudySumTimeList(userId,courseIds);
                if(ObjectUtils.isNotEmpty(coursePlayRecordList)){
                    Map<BigDecimal,CoursePlayRecord> coursePlayRecordMap = coursePlayRecordList.stream().collect(Collectors.toMap(e->e.getBuyCourseId(),e->e));
                    courseBuyRecordList.forEach(e->{
                        CoursePlayRecord playRecord = coursePlayRecordMap.get(e.getCourseId());
                        if(ObjectUtils.isNotEmpty(playRecord)){
                            e.setStudySumTime(playRecord.getDurationNum());
                        }
                    });
                }
            }
            //设置课程一周学习时间
            if(setWeekStudyTime) {
                List<CoursePlayRecord> coursePlayRecordList = coursePlayRecordBiz.queryUserWeekStudySumTimeList(userId, courseIds);
                if (ObjectUtils.isNotEmpty(coursePlayRecordList)) {
                    Map<BigDecimal, CoursePlayRecord> coursePlayRecordMap = coursePlayRecordList.stream().filter(e->ObjectUtils.isNotEmpty(e)).collect(Collectors.toMap(e -> e.getBuyCourseId(), e -> e));
                    courseBuyRecordList.forEach(e->{
                        CoursePlayRecord playRecord = coursePlayRecordMap.get(e.getCourseId());
                        if(ObjectUtils.isNotEmpty(playRecord)){
                            Integer weekDurationNum = playRecord.getWeekDurationNum();
                            e.setWeekStudyTime(weekDurationNum);
                        }
                    });
                }
            }
            //设置最后一个学习目录
            if(setLastStudyCatalog){
                Map<BigDecimal, CourseCatalog> courseCatalogMap = courseCatalogBiz.findUserCourseLastStudyCatalogMap(userId,courseIds);
                if(ObjectUtils.isNotEmpty(courseCatalogMap)){
                    courseBuyRecordList.forEach(e->{
                        CourseCatalog courseCatalog = courseCatalogMap.get(e.getCourseId());
                        e.setLastCourseCatalog(courseCatalog);
                    });
                }
            }
        }
        return courseBuyRecordList;
    }
    /**
     * 设置购买记录的学习进度
     * @param studySpeeds 学习节点数据列表
     * @param courseBuyRecord 购买记录对象
     */
    private void setCourseBuyRecordStudySpeed(List<UserBuyCourseStudySpeed> studySpeeds, CourseBuyRecord courseBuyRecord){
        Integer sumDuration = studySpeeds.stream().collect(Collectors.summingInt(UserBuyCourseStudySpeed::getDuration));

        //设置课程总时长
        Course course = courseBiz.findById(courseBuyRecord.getCourseId());
        Integer totleTimes = course.getTotleTimes();
        if(totleTimes == null){
            totleTimes = 0;
        }
        courseBuyRecord.setTotleTimes(totleTimes);

        //计算学习进度
        BigDecimal studySpeed = AmountUtils.safeDivide(sumDuration, totleTimes,4).multiply(new BigDecimal("100"));
        courseBuyRecord.setStudySpeed(String.valueOf(studySpeed.doubleValue()));
    }
    /**
     * 检测用户是否购买过该课程 （不限制过期时间）
     * @param userId
     * @param courseId
     * @return CourseBuyRecord 返回null则未购买过
     */
    public CourseBuyRecord checkUserBuyCourseNoValidity(BigDecimal userId,BigDecimal courseId){
        if(DataUtil.idIsNotNull(userId) && DataUtil.idIsNotNull(courseId)){
            StringBuilder whereSql = new StringBuilder(" courseId=");
            whereSql.append(courseId).append(" and userId = ").append(userId).append(" and courseStatus ='SUCCESS' order by updateTime desc");
            List<CourseBuyRecord> courseBuyRecordList = this.find(whereSql.toString(), null, null);
            if(ObjectUtils.isNotEmpty(courseBuyRecordList)){
                return courseBuyRecordList.get(0);
            }
        }
        return null;
    }
    /**
     * 获取SQL查询条件
     * @param courseBuyRecord
     * @return
     */
    private String getWhereSql(CourseBuyRecord courseBuyRecord){
        StringBuilder whereSql = new StringBuilder();
        whereSql.append( " validTime > '").append(DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss")).append("'");
        if(ObjectUtils.isNotEmpty(courseBuyRecord)){
            if(DataUtil.idIsNotNull(courseBuyRecord.getId())){
                whereSql .append(" and id = ").append(courseBuyRecord.getId());
            }
            if(ObjectUtils.isNotEmpty(courseBuyRecord.getCourseId())){
                whereSql .append(" and courseId=").append(courseBuyRecord.getCourseId());
            }
            if(StringUtils.isNotEmpty(courseBuyRecord.getCourseIds())){
                whereSql .append(" and courseId in (").append(courseBuyRecord.getCourseIds()).append(")");
            }
            if(ObjectUtils.isNotEmpty(courseBuyRecord.getUserId())){
                whereSql .append(" and userId = ").append(courseBuyRecord.getUserId());
            }
            if(StringUtils.isNotEmpty(courseBuyRecord.getOrderNo())){
                whereSql .append(" and orderNo = '").append(courseBuyRecord.getOrderNo()).append("'");
            }
            if(ObjectUtils.isNotEmpty(courseBuyRecord.getValidTime())){
                whereSql .append(" and validTime > '").append( DateUtils.format(courseBuyRecord.getValidTime(),"yyyy-MM-dd HH:mm:ss")).append("'");
            }
            if (StringUtils.isNotEmpty(courseBuyRecord.getCourseStatus())){
                whereSql .append(" and courseStatus ='").append(courseBuyRecord.getCourseStatus().trim()).append("'");
            }
            if(StringUtils.isNotEmpty(courseBuyRecord.getCourseTypeKey())){
                whereSql .append(" and courseTypeKey = '").append(courseBuyRecord.getCourseTypeKey()).append("'");
            }
            whereSql .append( " order by updateTime desc");
        }
        return whereSql.toString();
    }

    /**
     * 设置学习进度
     * @param data 购买记录
     */
    public void setLearnSchedule(List<CourseBuyRecord> data) {

    }

    /**
     * 分页查询用户购买记录
     * @param courseBuyRecord 查询条件
     * @param page 分页条件
     * @param setCourseData 是否设置课程
     * @return
     */
    public PageInfo<CourseBuyRecord> findCourseBuyRecordFrontPage(CourseBuyRecord courseBuyRecord, Pagination page, boolean setCourseData,
                                                                  boolean setTeacherData,
                                                                  boolean setProfileData,
                                                                  boolean setStudySpeed,
                                                                  boolean setStudySumTime,
                                                                  boolean setWeekStudyTime,
                                                                  boolean setLastStudyCatalog){
        PageHelper.startPage(page.getCurrentPage(),page.getPageSize());
        Page<CourseBuyRecord> coursePage =  courseBuyRecordDao.findCourseBuyRecordFrontPage(CourseBuyRecord.class,courseBuyRecord);
        PageInfo<CourseBuyRecord> courseBuyRecordPageInfo =  new PageInfo<>(coursePage);
        this.setCourseData(courseBuyRecordPageInfo.getList(),setCourseData, setTeacherData,setProfileData,setStudySpeed,setStudySumTime,setWeekStudyTime,setLastStudyCatalog);
        for(CourseBuyRecord courseBuyRecordTo :courseBuyRecordPageInfo.getList()){

            int i = DateUtils.daysBeforeNow(courseBuyRecordTo.getValidTime());
            if(i==0||i<0){
                courseBuyRecordTo.setValidHint("已过期");
            }else{
                courseBuyRecordTo.setValidHint(i+"天内可反复学习");
            }
        }
        return courseBuyRecordPageInfo;
    }


    /**
     * 分页查询用户购买记录
     * @param courseBuyRecordExpand 查询条件
     * @param page 分页条件
     * @return
     */
    public PageInfo<CourseBuyRecord> findCourseBuyRecordLearnPage(CourseBuyRecordExpand courseBuyRecordExpand, Pagination page){
        PageHelper.startPage(page.getCurrentPage(),page.getPageSize());
        Page<CourseBuyRecord> coursePage =  courseBuyRecordDao.findCourseBuyRecordFrontPage(CourseBuyRecord.class,courseBuyRecordExpand);
        PageInfo<CourseBuyRecord> courseBuyRecordPageInfo =  new PageInfo<>(coursePage);
        this.setCourseData(courseBuyRecordPageInfo.getList(),courseBuyRecordExpand.isSetCourseData(), false,false,courseBuyRecordExpand.isSetStudySpeed(),false,false,true);
        if(courseBuyRecordExpand.isVerifyPracticeHave()){
            this.setPracticeHave(courseBuyRecordPageInfo.getList(),courseBuyRecordExpand.getUserId());
        }
        for(CourseBuyRecord courseBuyRecordTo :courseBuyRecordPageInfo.getList()){

            int i = DateUtils.daysBeforeNow(courseBuyRecordTo.getValidTime());
            if(i==0||i<0){
                courseBuyRecordTo.setValidHint("已过期");
            }else{
                courseBuyRecordTo.setValidHint(i+"天内可反复学习");
            }
        }
        return courseBuyRecordPageInfo;
    }

    private  void setPracticeHave(List<CourseBuyRecord> courseBuyRecordList,BigDecimal userId){

        if(ObjectUtils.isNotEmpty(courseBuyRecordList)){
            //获取最后一次得答题记录
            Map  condition = new HashMap();
            String courseIds = courseBuyRecordList.stream().map(e->e.getCourseId().toString()).collect(Collectors.joining(","));

            condition.put("userId",userId);
            condition.put("courseIds",courseIds);
            List<ExamRecord> examRecordPracticeList = examRecordService.findExamRecordPracticeList(condition);
            List<String> courseList = examRecordPracticeList.stream().map(e -> e.getCourseIds()).collect(Collectors.toList());
            for(CourseBuyRecord entity:courseBuyRecordList){
                if(courseList.contains(entity.getCourseId().toString())){
                    entity.setPracticeHave(true);
                }
            }
        }
    }

}
